import React, { Component } from 'react'
import { Link } from 'react-router'
import { isEmpty, isUndefined } from 'lodash/fp'
import addEventListener from 'rc-util/lib/Dom/addEventListener'
import Scroll from 'react-scroll'
var LinkScroll = Scroll.Link
var Element = Scroll.Element
import {ReactPull} from 'react-alloytouch'
import 'react-alloytouch/sass/pull.scss'

import LoadingZ from 'components/LoadingZ'
import s from '../assets/ForumHome.scss'
class ForumHome extends Component {
  constructor (props) {
    super(props)
    this.state = {
      offers: [],
      typeId: 1,
      disablePullUp: false,
      page: 1
    }
  }

  componentDidMount () {
    const { fetchForumType, fetchForumList, loginStatus } = this.props
    fetchForumType()
    fetchForumList()
    loginStatus()
  }

  componentWillUnmount () {
    if (this.scrollEvent) {
      this.scrollEvent.remove()
    }
  }

  componentWillReceiveProps (nextProps) {
    const { color } = this.props
    const { forumHome } = nextProps
    const { forumList } = forumHome
    const { page } = this.state
    if (!isUndefined(forumList) && !isEmpty(forumList.items) && !isUndefined(forumList.items.result.data) && forumList.items.result.data.last_page && this.props.forumHome.forumList.isFetching !== forumList.isFetching) {
      let data = forumList.items.result.data
      let array = []
      for(var i in data) {
        if (/^\d+$/.test(i)) {
          data[i].color = color[parseInt(data[i].c_id) - 1]
          array.push(data[i])
        }
      }
      this.setState({
        offers: array
      })
      this.setState({
        offers: this.state.offers.concat(array),
        disablePullUp: false
      })
    } else if(!isUndefined(forumList) && !isEmpty(forumList.items) && !isEmpty(forumList.items) && !isUndefined(forumList.items.result.data) && !forumList.items.result.data.last_page && this.props.forumHome.forumList.isFetching !== forumList.isFetching) {
      let data = forumList.items.result.data
      let array = []
      for(var i in data) {
        if (/^\d+$/.test(i)) {
          data[i].color = color[parseInt(data[i].c_id) - 1]
          array.push(data[i])
        }
      }
      this.setState({
        offers: array
      })
      this.setState({
        offers: this.state.offers.concat(array),
        disablePullUp: true
      })
    }
  }

  handleClick(e, typeId) {
    const { fetchForumList } = this.props
    this.setState({
      typeId: typeId + 1,
      offers: [],
      disablePullUp: false,
      page: 1
    })
    fetchForumList(typeId + 1)
    this.props.changeRegion(typeId)
  }

  // refreshCallback = () => {
  //   return new Promise((resolve, reject) => {
  //     this.setState({
  //       disablePullUp: false
  //     })
  //     resolve()
  //     // setTimeout(() => {
  //     //   let result = false;
  //     //   if (Math.random() > 0.2) {
  //     //     result = true;
  //     //   }
  //     //   if (result) {
  //     //     this.setState({
  //     //       items: 30,
  //     //       disablePullUp: false
  //     //     }, () => {
  //     //       resolve();
  //     //     });
  //     //   } else {
  //     //     reject(new Error('错误'))
  //     //   }
  //     // }, 1000);
  //   }).then(() => {
  //     console.info('刷新成功！')
  //   }, () => {
  //     console.info('刷新失败！')
  //   });
  // }

  loadMoreCallback = () => {
    return new Promise((resolve, reject) => {
      const { fetchForumList } = this.props
      this.setState({
        disablePullUp: false,
        page: this.state.page + 1
      })
      if (this.state.page >= 2) {
        this.setState({
          disablePullUp: true,
        })
      }
      fetchForumList(this.state.typeId, this.state.page)
      resolve()
      // setTimeout(() => {
      //   let result = false;
      //   if (Math.random() > 0.2) {
      //     result = true;
      //   }
      //   if (result) {
      //     this.setState({
      //       items: this.state.items + 10,
      //       disablePullUp: this.state.items >= 60
      //     }, () => {
      //       resolve();
      //     });
      //   } else {
      //     reject(new Error('错误'))
      //   }
      // }, 1000);
    }).then(() => {
      // console.info('加载更多成功！')
    }, () => {
      // console.info('加载更多失败！')
    })
  }

  render () {
    const { forumHome, color } = this.props
    const { forumType } = forumHome
    const { forumList } = forumHome
    const { isFetching } = forumList
    const { attractionsRegionId } = forumHome
    const { disablePullUp, offers } = this.state
    const props = {
      // refreshCallback: this.refreshCallback,
      loadMoreCallback: this.loadMoreCallback,
      // refresh: true,
      loadMore: true,
      className: 'reactPull',
      disablePullUp
    }
    let typeItem = []
    if (!isUndefined(forumType) && !isEmpty(forumType.items) && forumType.items.result.data.length > 0) {
      forumType.items.result.data.map((item, i) => {
        typeItem.push({ color: color[i], c_name: item.item })
      })
    }
    return (
      <div>
        { isFetching && isUndefined(forumType.items.result) && isUndefined(forumList.items.result) && isEmpty(forumList.items.result) &&
          <div className='loading'>
            <LoadingZ />
          </div>
        }
        { !isFetching && !forumType.isFetching && !isEmpty(forumList) && !isEmpty(forumType.items) && !isUndefined(forumList.items.result) &&
          <div className={s.homeContent}>
            <div className={s.themeType}>
              { !isUndefined(forumType) && !isEmpty(forumType.items) && forumType.items.result.data.length > 0 && forumType.items.result.data.map((item, i) =>
                <a href='javascript:;' className={ isUndefined(attractionsRegionId) && i == 0 ? s.active : attractionsRegionId == i ? s.active : ''  } key={i} onClick={() => this.handleClick(item.c_name, i)}>{item.c_name}</a>
              )}
            </div>
            <ReactPull {...props}>
            <div className={s.forumList}>
              { !isUndefined(forumList) && !isEmpty(forumList.items) && !isUndefined(forumList.items.result) && !isEmpty(forumList.items.result.data) && offers.map((item, i) =>
                <Link to={ '/articleDetailed/' + item.content_id } className={s.item} key={i}>
                  <img src={item.u_headimg} />
                  <aside>{item.a_name}</aside>
                  <article>
                    <section>
                      <span style={{ background: item.color }}>{item.c_name}</span>
                      <span>{item.u_name}</span>
                    </section>
                  </article>
                  <i>{item.click_number}</i>
                </Link>
              )}
            </div>
            </ReactPull>
          </div>
        }
      </div>
    )
  }
}

ForumHome.propTypes = {

}

export default ForumHome
